package cn.ruleengine.core;

import cn.ruleengine.core.exception.ValueException;
import cn.ruleengine.core.rule.RuleSet;
import org.springframework.lang.NonNull;

import java.io.Closeable;
import java.util.Map;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;

/**
 * SlaServiceDeleteDTO
 * Copyright (c) 2021 WeiMai Technology, Inc.
 * All Rights Reserved.
 * Choice Proprietary and Confidential.
 *
 * @author: songyang
 * @date: 2021/8/3
 * @Description:
 */
public class RuleEngineRuleSetPublishCache implements Closeable {

    /**
     * 规则引擎规则集表缓存
     * <p>
     * key存放的是规则集id，value是外部code值
     * <p>
     */
    private final Map<Long, RuleSet> map = new ConcurrentHashMap<>();

    /**
     * 从引擎中删除一个映射
     *
     * @param id 映射规则集id
     */
    public void remove(Long id) {
        this.map.remove(id);
    }

    /**
     * 根据id从规则引擎中获取一个映射
     *
     * @param id id
     * @return 外部code
     */
    public RuleSet get(@NonNull Long id) {
        Objects.requireNonNull(id);
        if (!this.map.containsKey(id)) {
            throw new ValueException("No such variable：" + id);
        }
        return map.get(id);
    }

    /**
     * 往规则引擎中添加一个映射
     *
     * @param id    id
     * @param value 外部code
     */
    public void add(Long id, RuleSet value) {
        if (id == null || value == null) {
            throw new ValueException("Variable id or value cannot be Null");
        }
        this.map.put(id, value);
    }

    /**
     * 往规则引擎中添加多个映射
     *
     * @param multipleMap
     */
    public void addMultiple(@NonNull Map<Long, RuleSet> multipleMap) {
        multipleMap.forEach(this::add);
    }

    /**
     * size
     *
     * @return size
     */
    public int size() {
        return this.map.size();
    }

    /**
     * 清除规则引擎中所有的信息
     */
    @Override
    public void close() {
        this.map.clear();
    }

}
